"use client";
import React, { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { Project, getProject, getTasksByProjectId } from '@/controller/project';
import { toast } from 'sonner'
import { Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ArrowLeft } from 'lucide-react';
import SearchConfirmation from '@/components/project/search-confirmation';
import KeywordManager from '@/components/project/keyword-manager';
import Result from '@/components/project/result';
export default function ProjectPage() {
  const params = useParams();
  // 添加状态存储关键词和评估标准数据
  const [selectedKeywords, setSelectedKeyword] = useState<string[]>([]);
  const [project, setProject] = useState<Project | null>(null);
  const [isFromSearch, setIsFromSearch] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [evaluationCriteria, setEvaluationCriteria] = useState<string[]>([]);
  const id = params.id as string;
  useEffect(() => {
    // 当路由参数加载完成后，可以在这里处理与id相关的逻辑
    if (!id) {
      return;
    }

    const initProject = async () => {
      setIsLoading(true);
      try {
        const { data: project, error } = await getProject(id);
        if (error || !project) {
          toast.error('get project failed');
          return;
        }
        setProject(project)
        if (!project.search_keywords || !project.matching_rules) {
          setIsFromSearch(true)
          return;
        } else {
          setSelectedKeyword(project.search_keywords || [])
          setEvaluationCriteria(project.matching_rules || [])
          const { data: task, error: taskError } = await getTasksByProjectId(id);
          if (taskError || !task) {
            setIsFromSearch(true)
            return;
          }
          if (task?.task_type === 'content_search') {
            setIsFromSearch(false);
          } else {
            setIsFromSearch(true)
          }
        }
      } catch (error) {
        console.error('获取项目失败:', error);
      } finally {
        setIsLoading(false);
      }
    }

    initProject();
  }, [id]);

  // 处理确认搜索，接收从SearchConfirmation组件传递的数据
  const handleConfirmSearch = (selectedKeywords: string[]) => {
    setSelectedKeyword(selectedKeywords);

    // 隐藏SearchConfirmation组件
    setIsFromSearch(false)

  };
  return (
    <div className="relative">
      <div className="container mx-auto pt-3">
        <div className="flex items-center space-x-4">
          <Button variant="outline" size="icon">
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <h1 className="text-2xl font-bold truncate max-w-[80%]">{project?.name}</h1>
        </div>
        {/* 搜索确认区域 - 从弹窗移到页面中 */}
        {isFromSearch && id && !isLoading && (
          <SearchConfirmation
            id={id}
            initialKeywords={selectedKeywords}
            initialEvaluationCriteria={evaluationCriteria}
            onConfirmSearch={handleConfirmSearch}
          />
        )}
      </div>
      {!isFromSearch && !isLoading && (
        <KeywordManager
          initialKeywords={selectedKeywords}
          onKeywordsChange={(keywords: string[]) => {
            setSelectedKeyword(keywords);
          }}
          projectId={id}
        />
      )}
      {!isFromSearch && id && !isLoading && project && (
        <Result project={project} />
      )}
      {isLoading && (
        <div className="py-10 flex flex-col items-center justify-center text-gray-500">
          <Loader2 className="w-8 h-8 mb-2 animate-spin" />
          <p>Loading...</p>
        </div>
      )}
    </div>
  );
}
